package com.clw.service.impl;


import com.clw.dataobject.Buyer;
import com.clw.repository.BuyerRepository;
import com.clw.service.BuyerService;
import com.clw.service.BuyerService;
import com.clw.utils.DateUtils;
import com.clw.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017-12-15.
 */
@Service
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private BuyerRepository repository;

    @Override
    public boolean hasMore(String buyerName) {
        Buyer buyer=repository.findByName(buyerName);
        if (buyer!=null){
            return true;
        }
        return false;
    }

    @Override
    public List<Buyer> findAll() {
        return repository.findAll();
    }

    @Override
    public Buyer save(Buyer buyer) {
        return repository.save(buyer);
    }



    @Override
    public void del(Buyer buyer) {
        repository.delete(buyer);
    }

    @Override
    public Buyer add(Buyer buyer) {
        return repository.save(buyer);
    }

    @Override
    public Buyer findByBuyerName(String buyerName) {
        return repository.findByName(buyerName);
    }

    @Override
    public Buyer findOne(Integer id) {
        return repository.findOne(id);
    }

    @Override
    public Page<Buyer> findAll(String name, String phone, Pageable pageable) {
        return repository.findAll(getSpecification(name,phone),pageable);
    }

    @Override
    public Long getSize(String name, String phone) {
        return repository.count(getSpecification(name,phone));
    }

    private Specification<Buyer> getSpecification(String name,String phone){
        return new Specification<Buyer>() {
            @Override
            public Predicate toPredicate(Root<Buyer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates=new ArrayList<>();
                if (StringUtils.isNotEmpty(name)){
                    predicates.add(criteriaBuilder.like(root.get("name"),"%"+name+"%"));
                }
                if (StringUtils.isNotEmpty(phone)){
                    predicates.add(criteriaBuilder.like(root.get("phone"),"%"+phone+"%"));
                }
                return criteriaQuery.where(predicates.toArray
                        (new Predicate[predicates.size()])).getRestriction();
            }
        };
    }
}
